package com.fate.securecheckplatform.ui.acts;

import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.fate.securecheckplatform.IDCard.IDCardManager;
import com.fate.securecheckplatform.IDCard.IDCardModel;
import com.fate.securecheckplatform.IDCard.IDUtil;
import com.fate.securecheckplatform.R;
import com.fate.securecheckplatform.SecureCheckApplication;
import com.fate.securecheckplatform.adapters.AddRegisterAdapter;
import com.fate.securecheckplatform.base.BaseActivity;
import com.fate.securecheckplatform.bean.EventEntity;
import com.fate.securecheckplatform.bean.TableForbiddenPerformance;
import com.fate.securecheckplatform.bean.TableForbiddenThing;
import com.fate.securecheckplatform.bean.TableForbiddenType;
import com.fate.securecheckplatform.constant.Constant;
import com.fate.securecheckplatform.db.DataBase;
import com.fate.securecheckplatform.utils.ExecutorManager;
import com.fate.securecheckplatform.utils.FileUtil;
import com.fate.securecheckplatform.utils.GlideEngine;
import com.fate.securecheckplatform.utils.SpUtil;
import com.fate.securecheckplatform.utils.ToastUtil;
import com.fate.securecheckplatform.utils.Util;
import com.fate.securecheckplatform.views.ChooseForbiddenNameDialog;
import com.fate.securecheckplatform.views.ChooseOperationDialog;
import com.fate.securecheckplatform.views.RecyclerViewDivider;
import com.fate.securecheckplatform.views.SignView;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.internal.Utils;

import static com.fate.securecheckplatform.constant.Constant.VID;

/**
 * Author:   RandBII
 * DATE:   2020/1/9
 * Description: 添加 和修改公用一个页面
 */
public class AddRegisterActivity extends BaseActivity {

    @BindView(R.id.tv_login_name)
    TextView mTvLoginName;
    @BindView(R.id.ll_sign)
    LinearLayout mLLSign;
    @BindView(R.id.rv_object)
    RecyclerView mRvObject;

    @BindView(R.id.sv)
    SignView mSignView;
    @BindView(R.id.et_name)
    EditText mEtName;
    @BindView(R.id.et_phone)
    EditText mEtPhone;
    @BindView(R.id.et_id_card)
    EditText mEtIdCard;
    @BindView(R.id.et_address)
    EditText mEtAddress;
    @BindView(R.id.et_ticket_number)
    EditText mEtTicketNumber;
    @BindView(R.id.et_train_number)
    EditText mEtTrainNumber;
    @BindView(R.id.et_seat_number)
    EditText mEtSeatNumber;
    @BindView(R.id.et_start_station)
    EditText mEtStartStataion;
    @BindView(R.id.et_end_station)
    EditText mEtEndStation;
    @BindView(R.id.et_check_job)
    EditText mEtCheckJob;
    @BindView(R.id.tv_check_serial)
    TextView mTvCheckSerial;
    @BindView(R.id.et_check_person)
    EditText mEtCheckPersion;
    @BindView(R.id.et_resove_type)
    EditText mEtResolveType;
    @BindView(R.id.et_resolve_police)
    EditText mEtResolvePolice;
    @BindView(R.id.tv_is_document)
    TextView mTvIsDocument;

    AddRegisterAdapter adapter;
    TableForbiddenPerformance performance;
    String loginName;
    private String lkName;// 旅客姓名
    private String lkPhone;
    private String lkIdNumber;
    private String lkAddress;
    private String ticketNumber;
    private String trainNumber;
    private String seatNumber;
    private String startStation;
    private String endStation;
    private String checkJob;
    private String checkPerson;
    private String checkSerial;
    private String wetherDocument;
    private String resolveType;
    private String resolvePolice;
    private AlertDialog existDialog;
    private AlertDialog confirmDeleteDialog;
    private AlertDialog restSignDialog;
    private List<String> operationNames;
    private List<TableForbiddenType> thingTypes;//显示弹框
    private List<TableForbiddenThing> things = new ArrayList<>();
    private DataBase dataBase;
    private ChooseOperationDialog operationDialog;
    private ChooseOperationDialog documentDialog;
    private String[] isDocuments = {"是", "否"};
    private ChooseForbiddenNameDialog forbiddenNameDialog;
    private int imgPosition = -1;
    private int PAGE_MODE = 0; // 0 是添加模式 1 是编辑模式
    private String cardNum = "";
    // 身份证读取
    private IDCardManager manager;
    private ReadThread thread;
    private Context mContext = null;
    private UsbManager mUsbManager = null;
    private BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Constant.ACTION_USB_PERMISSION.equals(action)) {
                synchronized (this) {
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                        openDevice();
                    } else {
                        Toast.makeText(mContext, "USB未授权", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }
    };

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 0:
                    IDUtil.play(1, 0);
                    ToastUtil.toast("读身份证成功！");
                    Bundle bundle = msg.getData();
                    //获取身份证信息：姓名、性别、出生年、月、日、住址、身份证号、签发机关、有效期开始、结束、（额外信息新地址（一般情况为空））
                    String name = bundle.getString("name");
                    String sex = bundle.getString("sex");
                    String nation = bundle.getString("nation");
                    String year = bundle.getString("year");
                    String month = bundle.getString("month");
                    String day = bundle.getString("day");
                    String address = bundle.getString("address");
                    String id = bundle.getString("id");
                    String office = bundle.getString("office");
                    String start = bundle.getString("begin");
                    String stop = bundle.getString("end");
                    String newaddress = bundle.getString("newaddress");
                    String fp1 = bundle.getString("fp1");
                    String fp2 = bundle.getString("fp2");

                    mEtName.setText(name);
                    mEtIdCard.setText(id);
                    mEtAddress.setText(address);

                    break;
                case 1:

                    ToastUtil.toast("发现身份证!\n正在获取身份证数据...");
                    break;
                case 2:

                    break;
                case 3:

                    break;
                default:
                    break;
            }
        }

        ;
    };

    @Override
    protected int layoutResId() {
        return R.layout.activity_add_register;
    }

    @Override
    protected void initData() {
        doStart();
    }

    @Override
    protected void initView() {
        IDUtil.initSoundPool(AddRegisterActivity.this);
        if (thread == null) {
            thread = new ReadThread();
            thread.start();
        }
        dataBase = DataBase.getInstance(this);
        mContext = SecureCheckApplication.get();
        loginName = SpUtil.getInstance().getString(Constant.LOGIN_NAME);
        mTvLoginName.setText(TextUtils.isEmpty(loginName) ? "" : loginName);
        config();
        mRvObject.setHasFixedSize(true);
        mRvObject.setLayoutManager(new LinearLayoutManager(this));
        adapter = new AddRegisterAdapter(this, things);
        mRvObject.setAdapter(adapter);
        mRvObject.addItemDecoration(new RecyclerViewDivider(this));
        adapter.setOnItemClickListener((view, position) -> {

            switch (view.getId()) {
                case R.id.tv_name:
                    performNamePop(position);
                    break;
                case R.id.tv_operation:
                    performOperationPop(position);
                    break;
                case R.id.btn_delete_one:

                    confirmDeleteOne(position);

                    break;
                case R.id.iv_delete_pic:
                    imgPosition = position;
                    removeImg(position);
                    break;
                case R.id.iv_add_pic:
                    imgPosition = position;
                    picOneImg(position);
                    break;
            }
        });

    }

    private void removeImg(int position) {
        if (things != null && things.size() > 0) {
            TableForbiddenThing thing = things.get(imgPosition);
            thing.setWjpt(null);
            adapter.notifyDataSetChanged();
        }
    }

    /**
     * 选择一张图片
     *
     * @param position
     */
    @SuppressLint("SourceLockedOrientationActivity")
    private void picOneImg(int position) {
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                .loadImageEngine(GlideEngine.createGlideEngine())// 外部传入图片加载引擎，必传项
                .isWeChatStyle(true)// 是否开启微信图片选择风格
                .maxSelectNum(1)// 最大图片选择数量
                .minSelectNum(1)// 最小选择数量
                .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE)
                .compress(true)
                .forResult(PictureConfig.CHOOSE_REQUEST);

    }

    /**
     * 操作方式
     *
     * @param position
     */
    private void performOperationPop(int position) {
        operationDialog = new ChooseOperationDialog.Builder(this, operationNames)
                .setDatas(operationNames)
                .setCancleListener(v -> {

                        }
                ).setOnItemClickListener((view, p1) -> {
                    String oName = operationNames.get(p1);
                    TableForbiddenThing t = things.get(position);
                    t.setWpcz(oName);
                    adapter.notifyItemChanged(position);
                    operationDialog.dismiss();
                }).create();

        operationDialog.show();

    }

    /**
     * 是否立案
     */
    private void showIsDocumentPop() {
        documentDialog = new ChooseOperationDialog.Builder(this, Arrays.asList(isDocuments))
                .setDatas(operationNames)
                .setCancleListener(v -> {

                        }
                ).setOnItemClickListener((view, p1) -> {
                    String s = isDocuments[p1];
                    mTvIsDocument.setText(s);
                    documentDialog.dismiss();
                }).create();

        documentDialog.show();

    }

    /**
     * 展示选择名字的 弹框
     *
     * @param position
     */
    private void performNamePop(int position) {
        forbiddenNameDialog = new ChooseForbiddenNameDialog.Builder(this, thingTypes)
                .setCancleListener(v -> {
                        }
                ).setOnItemClickListener((view, p1) -> {
                    TableForbiddenType type = thingTypes.get(p1);
                    TableForbiddenThing thing = things.get(position);
                    thing.setWjpmc(type.getZdmc());
                    adapter.notifyItemChanged(position);
                    forbiddenNameDialog.dismiss();
                }).create();
        forbiddenNameDialog.show();

    }

    private void config() {
        performance = (TableForbiddenPerformance) getIntent().getSerializableExtra(Constant.DATA_PERFORMANCE);
        if (performance != null) { // 说明是编辑页面
            PAGE_MODE = 1;
            fillDataToView(performance);
        } else { // 添加页面
            things = new ArrayList<>();
            things.add(new TableForbiddenThing());
            Future<Integer> f = ExecutorManager.getService().submit(() -> dataBase.forbiddenObjectDao().getPerformancesCountByDay(Util.getCurrentDate()));
            Integer i = null;
            try {
                i = f.get();
            } catch (ExecutionException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (i == null) i = 0;
            mTvCheckSerial.setText(Util.genericCheckSerial(i));
        }


        operationNames = Arrays.asList(getResources().getStringArray(R.array.operation_name));

        Future<List<TableForbiddenType>> future = ExecutorManager.getService().submit(() -> dataBase.forbiddenTypeDao().getAllTypes());
        try {
            thingTypes = future.get();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    private void fillDataToView(TableForbiddenPerformance performance) {
        mLLSign.setVisibility(View.GONE);
        mEtName.setText(Util.toFillView(performance.getLkxm()));
        mEtPhone.setText(Util.toFillView(performance.getLxfs()));
        mEtIdCard.setText(Util.toFillView(performance.getSfzh()));
        mEtAddress.setText(Util.toFillView(performance.getLkdz()));
        mEtTicketNumber.setText(Util.toFillView(performance.getPh()));
        mEtTrainNumber.setText(Util.toFillView(performance.getCc()));
        mEtSeatNumber.setText(Util.toFillView(performance.getXb()));
        mEtStartStataion.setText(Util.toFillView(performance.getQsz()));
        mEtEndStation.setText(Util.toFillView(performance.getZdz()));
        mTvCheckSerial.setText(Util.toFillView(performance.getCzbh()));
        mEtCheckJob.setText(Util.toFillView(performance.getJcgw()));
        mEtCheckPersion.setText(Util.toFillView(performance.getJcry()));
        mEtResolvePolice.setText(Util.toFillView(performance.getCzmj()));
        mEtResolveType.setText(Util.toFillView(performance.getCzfs()));
        mEtCheckPersion.setText(Util.toFillView(performance.getJcry()));
        if ("1".equals(performance.getSfla())) {
            mTvIsDocument.setText("是");
        } else {
            mTvIsDocument.setText("否");
        }
        things = performance.getThins();
    }

    /**
     * 退出登录的弹框
     */
    private void showExistDialog() {
        existDialog = new AlertDialog.Builder(AddRegisterActivity.this)
                .setTitle("退出程序")
                .setMessage("是否退出程序")
                .setPositiveButton("确定", (dialogInterface, i) -> {
                    SpUtil.getInstance().putString(Constant.LOGIN_NAME, "");
                    SecureCheckApplication.get().exit();
                })
                .setNegativeButton("取消", (dialogInterface, i) -> {
                    existDialog.dismiss();
                }).create();
        existDialog.show();
    }

    /**
     * 确定删除
     *
     * @param position
     */
    private void confirmDeleteOne(int position) {
        confirmDeleteDialog = new AlertDialog.Builder(AddRegisterActivity.this)
                .setTitle("删除")
                .setMessage("是否删除本条")
                .setPositiveButton("确定", (dialogInterface, i) -> {
                    if (things != null && things.size() > 0) {
                        things.remove(position);
                        adapter.notifyDataSetChanged();
                    }
                })
                .setNegativeButton("取消", (dialogInterface, i) -> {
                    confirmDeleteDialog.dismiss();
                }).create();
        confirmDeleteDialog.show();
    }

    /**
     * 确定重新签名
     */
    private void confirmRest() {
        restSignDialog = new AlertDialog.Builder(AddRegisterActivity.this)
                .setTitle("签名信息")
                .setMessage("确认清空签名信息？")
                .setPositiveButton("确定", (dialogInterface, i) -> {
                    mSignView.clearStep();
                })
                .setNegativeButton("取消", (dialogInterface, i) -> {
                    restSignDialog.dismiss();
                }).create();
        restSignDialog.show();
    }

    @OnClick({R.id.tv_cancel, R.id.tv_save, R.id.tv_add_one, R.id.iv_shut_down,
            R.id.tv_reset,
            R.id.tv_is_document,
            R.id.tv_read_card})
    public void onClickEvent(View v) {
        switch (v.getId()) {
            case R.id.tv_cancel:
                finish();
                break;
            case R.id.tv_save:
                saveOnePerformance();
                break;
            case R.id.tv_add_one:
                things.add(new TableForbiddenThing());
                adapter.notifyDataSetChanged();
                break;
            case R.id.iv_shut_down:
                showExistDialog();
                break;
            case R.id.tv_reset:
                confirmRest();
                break;
            case R.id.tv_is_document:
                showIsDocumentPop();
                break;
            case R.id.tv_read_card:
                toReadCard();
                break;
        }

    }

    /**
     * 开启读卡功能
     */
    private void toReadCard() {
        openDevice();
    }

    /**
     * 保存一条记录
     */
    private void saveOnePerformance() {

        if (checkItems()) {
            if (performance == null) {
                performance = new TableForbiddenPerformance();
            }
            performance.setLkxm(lkName);
            performance.setLxfs(lkPhone);
            performance.setLkdz(lkAddress);
            performance.setSfzh(lkIdNumber);
            performance.setCc(trainNumber);
            performance.setPh(ticketNumber);
            performance.setRksj(Util.getFormatCurrentTime());
            performance.setQsz(startStation);
            performance.setZdz(endStation);
            performance.setXb(seatNumber);

            performance.setCzmj(resolvePolice);
            performance.setCzfs(resolveType);
            performance.setCzbh(checkSerial);
            performance.setJcry(checkPerson);
            performance.setJcgw(checkJob);
            performance.setDayTime(Util.getCurrentDate());
            if (things != null && things.size() > 0) {
                for (TableForbiddenThing t : things) {
                    if (TextUtils.equals("移入暂存库", t.getWpcz()) ||
                            TextUtils.equals("1", t.getWpcz())) {
                        t.setWpcz("1");
                    } else if (TextUtils.equals("移入危险库", t.getWpcz()) ||
                            TextUtils.equals("2", t.getWpcz())) {
                        t.setWpcz("2");
                    } else if (TextUtils.equals("民警处置", t.getWpcz()) ||
                            TextUtils.equals("3", t.getWpcz())) {
                        t.setWpcz("3");
                    }
                }
            }
            performance.setThins(things);

            if (TextUtils.equals("是", wetherDocument)) { // 是否立案
                performance.setSfla("1");
            } else {
                performance.setSfla("0");
            }
            performance.setCzry(TextUtils.isEmpty(loginName) ? "" : loginName);
            performance.setRkjsr(TextUtils.isEmpty(loginName) ? "" : loginName);
            performance.setAndroidSelected(false); // 用来标记上个页面的
            if (PAGE_MODE == 0) { // 增加模式
                if (mSignView != null && mSignView.isSigned()) {
                    String signPath = FileUtil.viewSaveToImage(mSignView, lkIdNumber + "_sign");
                    performance.setLkqmt(signPath);
                }

                ExecutorManager.getService().execute(() -> {
                    dataBase.forbiddenObjectDao().addOneForbiddenPerformance(performance);
                });
            } else { // 编辑模式
                ExecutorManager.getService().execute(() -> {
                    dataBase.forbiddenObjectDao().updateOnePerformance(performance);
                });
            }


            EventBus.getDefault().post(new EventEntity(Constant.CODE_REFRESH_REGSITER_FRAGMENT));
            EventBus.getDefault().post(new EventEntity(Constant.CODE_REFRESH_OBTAIN_FRAGMENT));
            navigateToPrint();
            finish();
        }
    }

    private void navigateToPrint() {
        Intent intent = new Intent(this, MyPrintActivity.class);
        intent.putExtra(Constant.DATA_PRINT, performance);
        startActivity(intent);
    }

    /**
     * 检查输入的必要项
     *
     * @return
     */
    private boolean checkItems() {
        lkName = mEtName.getText().toString().trim();
        lkIdNumber = mEtIdCard.getText().toString().trim();
        lkPhone = mEtPhone.getText().toString().trim();
        lkAddress = mEtAddress.getText().toString().trim();
        trainNumber = mEtTrainNumber.getText().toString().trim();
        ticketNumber = mEtTicketNumber.getText().toString().trim();
        seatNumber = mEtSeatNumber.getText().toString().trim();
        startStation = mEtStartStataion.getText().toString().trim();
        endStation = mEtEndStation.getText().toString().trim();
        checkJob = mEtCheckJob.getText().toString().trim();
        checkPerson = mEtCheckPersion.getText().toString().trim();
        checkSerial = mTvCheckSerial.getText().toString().trim();
        resolvePolice = mEtResolvePolice.getText().toString().trim();
        resolveType = mEtResolveType.getText().toString().trim();
        wetherDocument = mTvIsDocument.getText().toString().trim();

        if (TextUtils.isEmpty(lkName)) {
            ToastUtil.toast("请输入姓名");
            return false;
        }
        if (TextUtils.isEmpty(lkIdNumber)) {
            ToastUtil.toast("请输入身份证号");
            return false;
        }
        // TODO 身份证正则判断
//        if (!Util.isIDNumber(lkIdNumber)) {
//            ToastUtil.toast("请输入正确身份证号");
//            return false;
//        }
        if (TextUtils.isEmpty(lkPhone)) {
            ToastUtil.toast("请输入电话号码");
            return false;
        }
        if (TextUtils.isEmpty(lkAddress)) {
            ToastUtil.toast("请输入地址");
            return false;
        }
        if (TextUtils.isEmpty(trainNumber)) {
            ToastUtil.toast("车次信息");
            return false;
        }
        if (TextUtils.isEmpty(seatNumber)) {
            ToastUtil.toast("席别信息");
            return false;
        }
        if (things == null || things.size() == 0) {
            ToastUtil.toast("请录入危险品信息");
            return false;
        }

        if (TextUtils.isEmpty(things.get(0).getWjpmc()) ||
                TextUtils.isEmpty(things.get(0).getWjpsl())) {
            ToastUtil.toast("危险品信息请录入完整");
            return false;
        }


        return true;
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    List<LocalMedia> m = PictureSelector.obtainMultipleResult(data);
                    String path = m.get(0).getCompressPath();
                    if (imgPosition != -1 && things.size() > 0) {
                        TableForbiddenThing thing = things.get(imgPosition);
                        thing.setWjpt(path);
                    }

                    adapter.notifyDataSetChanged();
                    break;
            }
        }
    }


    public void openDevice() {

        if (manager == null) {
            manager = new IDCardManager(AddRegisterActivity.this);
        }
        startFlag = true;

    }

    private void requestDevicePermission() {
        mUsbManager = (UsbManager) this.getSystemService(Context.USB_SERVICE);
        IntentFilter filter = new IntentFilter();
        filter.addAction(Constant.ACTION_USB_PERMISSION);
        filter.addAction(UsbManager.ACTION_USB_ACCESSORY_ATTACHED);
        mContext.registerReceiver(mUsbReceiver, filter);

        for (UsbDevice device : mUsbManager.getDeviceList().values()) {
            if (device.getVendorId() == VID && device.getProductId() == Constant.PID) {
                Intent intent = new Intent(Constant.ACTION_USB_PERMISSION);
                PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
                mUsbManager.requestPermission(device, pendingIntent);
            }
        }
    }

    private void doStart() {

        requestDevicePermission();
    }

    private void doStop() {

    }

    @Override
    protected void onDestroy() {
        doStop();
        if (mUsbManager != null) {
            mContext.unregisterReceiver(mUsbReceiver);
        }
        closeReadId();
        super.onDestroy();

    }

    private boolean runFlag = true;
    private boolean startFlag = false;

    private class ReadThread extends Thread {
        @Override
        public void run() {
            while (runFlag) {
//                Log.e("AA---", "-");
                if (startFlag && manager != null) {
                    if (manager.findCard(200)) {
                        handler.sendEmptyMessage(1);
                        IDCardModel model = null;
                        long time = System.currentTimeMillis();

                        //获取身份证信息、图像
                        model = manager.getData(2000);
                        if (model != null) {
                            sendMessage(model.getName(), model.getSex(), model.getNation(),
                                    model.getYear(), model.getMonth(), model.getDay(),
                                    model.getAddress(), model.getIDCardNumber(), model.getOffice(),
                                    model.getBeginTime(), model.getEndTime(), model.getOtherData(),
                                    model.getPhotoBitmap(), "未读出指纹数据", "未读出指纹数据");
                        }

                    }
                }

                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            super.run();
        }

        private void sendMessage(String name, String sex, String nation,
                                 String year, String month, String day, String address, String id,
                                 String office, String start, String stop, String newaddress
                , Bitmap bitmap, String fp1, String fp2) {
            Message message = new Message();
            Bundle bundle = new Bundle();
            bundle.putString("name", name);
            bundle.putString("sex", sex);
            bundle.putString("nation", nation);
            bundle.putString("year", year);
            bundle.putString("month", month);
            bundle.putString("day", day);
            bundle.putString("address", address);
            bundle.putString("id", id);
            bundle.putString("office", office);
            bundle.putString("begin", start);
            bundle.putString("end", stop);
            bundle.putString("newaddress", newaddress);
            bundle.putString("fp1", fp1);
            bundle.putString("fp2", fp2);

            message.setData(bundle);
            handler.sendMessage(message);
        }
    }


    @Override
    public void onPause() {
        super.onPause();
        if (!pasue && manager != null) {
            pasue = true;
            manager.close();
            manager = null;
            startFlag = false;
        }
    }

    //app暂停
    private boolean pasue = false;

    @Override
    public void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        if (pasue) {
            pasue = false;
            if (manager == null) {
                manager = new IDCardManager(AddRegisterActivity.this);
            }
            startFlag = true;
        }
    }

    public void closeReadId() {
        startFlag = false;

        if (manager != null) {
            manager.close();
            manager = null;
        }
    }

}
